package myky.com.doctorapp.ui

import android.content.Intent
import android.support.v7.widget.LinearLayoutManager
import android.text.Editable
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import com.blankj.utilcode.util.KeyboardUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.github.nukc.stateview.Constant
import com.gyf.barlibrary.ImmersionBar
import kotlinx.android.synthetic.main.activity_search.*
import myky.com.adapter.SearchResultAdapter
import myky.com.doctorapp.R
import myky.com.doctorapp.adapter.SearchDiseaseResultAdapter
import myky.com.doctorapp.entity.SearchHistoryItem
import myky.com.doctorapp.base.BaseActivity
import myky.com.doctorapp.base.CMApplication
import myky.com.doctorapp.contract.SearchContract
import myky.com.doctorapp.entity.QuikSearchEntity
import myky.com.doctorapp.presenter.SearchPresenter
import myky.com.doctorapp.utils.Constants
import myky.com.doctorapp.utils.ShareUtil
import myky.com.doctorapp.utils.SimpleWatcher
import java.util.ArrayList

/**
 * Description: 搜索类
 * @author xiangyao
 * Created by 2019/3/4 5:58 PM
 */
class SearchActivity : BaseActivity<SearchPresenter, List<SearchHistoryItem>>(), SearchContract.View, SearchResultAdapter.OnTagClicListener, View.OnKeyListener, BaseQuickAdapter.OnItemChildClickListener {


    private var fromType: Int = 0

    lateinit var quikSearchEntities: ArrayList<QuikSearchEntity>

    lateinit var searchDiseaseResultAdapter: SearchDiseaseResultAdapter

    var userID:Int = -1

    override fun onKey(p0: View?, p1: Int, p2: KeyEvent): Boolean {

        // TODO Auto-generated method stub
        // 修改回车键功能
        if (p1 == KeyEvent.KEYCODE_ENTER && p2.action == KeyEvent.ACTION_DOWN) {
            // 先隐藏键盘
            (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
                    .hideSoftInputFromWindow(this@SearchActivity
                            .currentFocus.windowToken,
                            InputMethodManager.HIDE_NOT_ALWAYS)
            //接下来在这里做你自己想要做的事，实现自己的业务。
            val searchContent = act_search_et_search.text.toString()
            val intent = Intent(this@SearchActivity, DoctorListActivity::class.java)
            intent.putExtra("fromType", fromType)
            intent.putExtra(Constant.COMOONBUNDLEKEY, searchContent)
            startActivity(intent)
            act_search_et_search.setText("")
        }
        return false

    }



    override fun showReleaedKeyWord(keyWord: MutableList<String>) {
        quikSearchEntities.clear()
        if (keyWord.size > 0) {
            for (value in keyWord) {
                val quikSearchEntity = QuikSearchEntity()
                quikSearchEntity.keyword = act_search_et_search.text.toString()
                quikSearchEntity.resultWord = value
                quikSearchEntities.add(quikSearchEntity)
            }
            searchTips.visibility = View.VISIBLE
            historyLayout.visibility = View.GONE
            act_search_clearinput.visibility=View.VISIBLE
            searchDiseaseResultAdapter.notifyDataSetChanged()

        } else {
            searchTips.visibility = View.GONE
            historyLayout.visibility = View.VISIBLE
            act_search_clearinput.visibility=View.GONE
        }

    }





    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {

        when(view?.id){
            R.id.rootLayout->{

                KeyboardUtils.hideSoftInput(this)

                val data = searchDiseaseResultAdapter.data

                val resultWord = data[position].resultWord

                val intent = Intent(this@SearchActivity, DoctorListActivity::class.java)
                intent.putExtra(Constants.INTENT_TYPE, fromType)
                intent.putExtra(Constant.COMOONBUNDLEKEY, resultWord)
                startActivity(intent)
            }

        }

    }



    override fun onTagClick(seachContent: String) {

        val intent = Intent(this@SearchActivity, DoctorListActivity::class.java)
        intent.putExtra(Constants.INTENTTYPE, fromType)
        intent.putExtra(Constant.COMOONBUNDLEKEY, seachContent)
        startActivity(intent)
    }

    override fun deleteCallBack(id: Int, postion: Int) {

        val userId = ShareUtil.getInt(Constants.USERID)


        mPresenter.deleteSingleHistoryById(id,Constants.CURRENTVERSION,userId.toString(),postion)

    }

    lateinit var searchResultAdapter: SearchResultAdapter
    private val searchList = ArrayList<SearchHistoryItem>()

    override fun reloadActivity() {
    }

    override fun injectTarget(): View = findViewById(R.id.injectView)

    override fun initData() {
        val loginOk = CMApplication.getInstance().isLoginOk


        userID = ShareUtil.getInt(Constants.USERID)


        if (loginOk) {
            searchResultAdapter = SearchResultAdapter(this, searchList)
            id_flowlayout.adapter = searchResultAdapter
            searchResultAdapter.setOnTagClicListener(this)
            mPresenter.getSearchHistory("v1.0", "0", userID.toString())
        }

    }

    override fun initView() {
        ImmersionBar.with(this).keyboardEnable(true).fitsSystemWindows(true)
                .statusBarColor(R.color.white).statusBarDarkFont(true, 0.2f).init()

        quikSearchEntities = ArrayList()
        searchDiseaseResultAdapter = SearchDiseaseResultAdapter(quikSearchEntities)
        listView.layoutManager = LinearLayoutManager(this)
        listView.adapter = searchDiseaseResultAdapter
        searchDiseaseResultAdapter.onItemChildClickListener = this

        fromType = intent.getIntExtra("fromType", 0)
        act_search_et_search.setOnKeyListener(this)



        act_search_et_search.addTextChangedListener(object : SimpleWatcher() {
            override fun afterTextChangedSimple(var1: Editable?) {

                if (act_search_et_search.text.isNotEmpty()) {
                    act_search_clearinput.visibility = View.GONE

                    val toString = act_search_et_search.text.toString()

                    mPresenter.findKeyWordByInput("v1.0", fromType.toString(), toString)
                } else {

                    historyLayout.visibility = View.VISIBLE
                    searchTips.visibility = View.GONE
                    quikSearchEntities.clear()
                    act_search_clearinput.visibility=View.GONE
                }
            }
        })

        act_search_clearinput.setOnClickListener {
            act_search_et_search.setText("")

            searchTips.visibility = View.GONE

            historyLayout.visibility = View.VISIBLE

            act_search_clearinput.visibility=View.GONE

        }

    }

    override fun getPresenter(): SearchPresenter = SearchPresenter()

    override fun getContenView(): Int = R.layout.activity_search

    override fun showDataSuccess(datas: List<SearchHistoryItem>?) {
    }

    override fun showAllHistory(allHistory: ArrayList<SearchHistoryItem>) {
        searchList.clear()

        searchList.addAll(allHistory)

        searchResultAdapter.notifyDataChanged()
    }

    override fun deleteSingleHistorySucced(position: Int) {

        searchList.removeAt(position)
        searchResultAdapter.notifyDataChanged()
    }

    override fun deleteAllHistorySucced() {
    }
}
